/**
 * 科技感粒子效果
 */
export class ParticleEffect {
  constructor(containerId) {
    this.container = document.getElementById(containerId);
    this.particles = [];
    this.canvas = null;
    this.ctx = null;
    this.isRunning = false;
    this.resizeTimeout = null;
  }

  // 初始化粒子效果
  init() {
    if (!this.container) return;

    // 创建Canvas元素
    this.canvas = document.createElement('canvas');
    this.ctx = this.canvas.getContext('2d');
    this.canvas.style.position = 'absolute';
    this.canvas.style.top = '0';
    this.canvas.style.left = '0';
    this.canvas.style.pointerEvents = 'none';
    this.canvas.style.zIndex = '1';
    this.container.appendChild(this.canvas);

    // 调整Canvas大小
    this.resizeCanvas();

    // 创建粒子
    this.createParticles();

    // 开始动画循环
    this.start();

    // 添加窗口大小变化监听
    window.addEventListener('resize', () => {
      clearTimeout(this.resizeTimeout);
      this.resizeTimeout = setTimeout(() => {
        this.resizeCanvas();
      }, 100);
    });
  }

  // 调整Canvas大小
  resizeCanvas() {
    if (!this.canvas || !this.container) return;
    
    const { width, height } = this.container.getBoundingClientRect();
    this.canvas.width = width;
    this.canvas.height = height;
  }

  // 创建粒子
  createParticles() {
    if (!this.canvas) return;

    // 清空现有粒子
    this.particles = [];

    // 根据Canvas大小确定粒子数量
    const particleCount = Math.floor((this.canvas.width * this.canvas.height) / 10000);

    for (let i = 0; i < particleCount; i++) {
      this.particles.push({
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        size: Math.random() * 2 + 0.5,
        speedX: (Math.random() - 0.5) * 0.3,
        speedY: (Math.random() - 0.5) * 0.3,
        alpha: Math.random() * 0.5 + 0.1,
        color: this.getRandomParticleColor()
      });
    }
  }

  // 获取随机粒子颜色
  getRandomParticleColor() {
    // 主要使用科技感的蓝色和青色系
    const colors = [
      'rgba(0, 188, 212, alpha)',
      'rgba(33, 150, 243, alpha)',
      'rgba(95, 217, 255, alpha)',
      'rgba(149, 230, 255, alpha)'
    ];
    
    const color = colors[Math.floor(Math.random() * colors.length)];
    return color.replace('alpha', this.particles[this.particles.length - 1]?.alpha || 0.3);
  }

  // 更新粒子位置
  update() {
    if (!this.ctx || !this.canvas) return;

    // 清空画布
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // 更新并绘制每个粒子
    this.particles.forEach(particle => {
      // 更新位置
      particle.x += particle.speedX;
      particle.y += particle.speedY;

      // 边界检测，使粒子在Canvas内循环
      if (particle.x < 0) particle.x = this.canvas.width;
      if (particle.x > this.canvas.width) particle.x = 0;
      if (particle.y < 0) particle.y = this.canvas.height;
      if (particle.y > this.canvas.height) particle.y = 0;

      // 绘制粒子
      this.ctx.beginPath();
      this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
      this.ctx.fillStyle = particle.color;
      this.ctx.fill();
    });

    // 绘制粒子之间的连线
    this.drawConnections();
  }

  // 绘制粒子之间的连线
  drawConnections() {
    if (!this.ctx) return;

    // 连线最大距离
    const maxDistance = 100;

    // 遍历所有粒子组合
    for (let i = 0; i < this.particles.length; i++) {
      for (let j = i + 1; j < this.particles.length; j++) {
        const dx = this.particles[i].x - this.particles[j].x;
        const dy = this.particles[i].y - this.particles[j].y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        // 如果粒子之间的距离在最大距离内，绘制连线
        if (distance < maxDistance) {
          // 连线的透明度根据距离变化
          const opacity = (maxDistance - distance) / maxDistance * 0.2;
          
          this.ctx.beginPath();
          this.ctx.strokeStyle = `rgba(0, 188, 212, ${opacity})`;
          this.ctx.lineWidth = 0.5;
          this.ctx.moveTo(this.particles[i].x, this.particles[i].y);
          this.ctx.lineTo(this.particles[j].x, this.particles[j].y);
          this.ctx.stroke();
        }
      }
    }
  }

  // 开始动画循环
  start() {
    if (this.isRunning) return;
    
    this.isRunning = true;
    this.animate();
  }

  // 动画循环
  animate() {
    if (!this.isRunning) return;
    
    this.update();
    requestAnimationFrame(() => this.animate());
  }

  // 停止动画
  stop() {
    this.isRunning = false;
  }

  // 销毁粒子效果
  destroy() {
    this.stop();
    
    try {
      if (this.canvas && this.container && this.container.contains(this.canvas)) {
        this.container.removeChild(this.canvas);
      }
      
      this.canvas = null;
      this.ctx = null;
      this.particles = [];
      
      if (this.resizeTimeout) {
        clearTimeout(this.resizeTimeout);
      }
    } catch (error) {
      console.error('Error destroying ParticleEffect:', error);
    }
  }
}

/**
 * 创建技术线条背景效果
 */
export class TechLinesEffect {
  constructor(containerId) {
    this.containerId = containerId;
    this.container = null;
    this.lines = [];
    this.canvas = null;
    this.ctx = null;
    this.isRunning = false;
    this.resizeTimeout = null;
  }

  // 初始化技术线条效果
  init() {
    try {
      this.container = document.getElementById(this.containerId);
      if (!this.container) {
        console.warn(`TechLinesEffect: Container with id '${this.containerId}' not found`);
        return;
      }

      // 创建Canvas元素
      this.canvas = document.createElement('canvas');
      this.ctx = this.canvas.getContext('2d');
      this.canvas.style.position = 'absolute';
      this.canvas.style.top = '0';
      this.canvas.style.left = '0';
      this.canvas.style.pointerEvents = 'none';
      this.canvas.style.zIndex = '0';
      this.container.appendChild(this.canvas);

      // 调整Canvas大小
      this.resizeCanvas();

      // 创建线条
      this.createLines();

      // 开始动画循环
      this.start();

      // 添加窗口大小变化监听
      window.addEventListener('resize', () => {
        clearTimeout(this.resizeTimeout);
        this.resizeTimeout = setTimeout(() => {
          this.resizeCanvas();
          this.createLines();
        }, 100);
      });
    } catch (error) {
      console.error('Error initializing TechLinesEffect:', error);
    }
  }

  // 调整Canvas大小
  resizeCanvas() {
    if (!this.canvas || !this.container) return;
    
    const { width, height } = this.container.getBoundingClientRect();
    this.canvas.width = width;
    this.canvas.height = height;
  }

  // 创建技术线条
  createLines() {
    if (!this.canvas) return;

    // 清空现有线条
    this.lines = [];

    // 创建水平线条
    const horizontalLinesCount = Math.floor(this.canvas.height / 80);
    for (let i = 0; i < horizontalLinesCount; i++) {
      const y = (i + 0.5) * (this.canvas.height / horizontalLinesCount);
      this.lines.push({
        type: 'horizontal',
        y: y,
        opacity: Math.random() * 0.1 + 0.05,
        offset: Math.random() * this.canvas.width,
        speed: Math.random() * 0.5 + 0.2
      });
    }

    // 创建垂直线条
    const verticalLinesCount = Math.floor(this.canvas.width / 80);
    for (let i = 0; i < verticalLinesCount; i++) {
      const x = (i + 0.5) * (this.canvas.width / verticalLinesCount);
      this.lines.push({
        type: 'vertical',
        x: x,
        opacity: Math.random() * 0.1 + 0.05,
        offset: Math.random() * this.canvas.height,
        speed: Math.random() * 0.3 + 0.1
      });
    }
  }

  // 更新线条位置
  update() {
    if (!this.ctx || !this.canvas) return;

    // 清空画布
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // 更新并绘制每条线条
    this.lines.forEach(line => {
      if (line.type === 'horizontal') {
        // 更新水平线条的偏移量
        line.offset = (line.offset + line.speed) % this.canvas.width;
        
        // 绘制水平线条
        this.ctx.beginPath();
        this.ctx.strokeStyle = `rgba(0, 188, 212, ${line.opacity})`;
        this.ctx.lineWidth = 1;
        
        // 绘制两条线段以创建无缝循环效果
        this.ctx.moveTo(line.offset - this.canvas.width, line.y);
        this.ctx.lineTo(line.offset, line.y);
        this.ctx.stroke();
      } else if (line.type === 'vertical') {
        // 更新垂直线条的偏移量
        line.offset = (line.offset + line.speed) % this.canvas.height;
        
        // 绘制垂直线条
        this.ctx.beginPath();
        this.ctx.strokeStyle = `rgba(33, 150, 243, ${line.opacity})`;
        this.ctx.lineWidth = 1;
        
        // 绘制两条线段以创建无缝循环效果
        this.ctx.moveTo(line.x, line.offset - this.canvas.height);
        this.ctx.lineTo(line.x, line.offset);
        this.ctx.stroke();
      }
    });
  }

  // 开始动画循环
  start() {
    if (this.isRunning) return;
    
    this.isRunning = true;
    this.animate();
  }

  // 动画循环
  animate() {
    if (!this.isRunning) return;
    
    this.update();
    requestAnimationFrame(() => this.animate());
  }

  // 停止动画
  stop() {
    this.isRunning = false;
  }

  // 销毁线条效果
  destroy() {
    this.stop();
    
    try {
      if (this.canvas && this.container && this.container.contains(this.canvas)) {
        this.container.removeChild(this.canvas);
      }
      
      this.canvas = null;
      this.ctx = null;
      this.lines = [];
      this.container = null;
      
      if (this.resizeTimeout) {
        clearTimeout(this.resizeTimeout);
      }
    } catch (error) {
      console.error('Error destroying TechLinesEffect:', error);
    }
  }
}